#!/usr/bin/env python
# coding=utf-8
import json

def get_stored_username():
    """如果以前存储了用户名就加载它""" 
    try:
        filename = 'username.json'
        # 以一个对象f_obj的方式打开文件filename
        with open(filename) as f_obj:
            print(type(f_obj))
            print(dir(f_obj))
            print(f_obj.__dict__)
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """提示用户输入用户名并存储它"""
    # 获取用户输入的用户名
    username = input("What is your name?")
    # 存储用户输入的用户名到username.json
    filename = 'username.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
    # 返回用户名
    return username

def greet_user():
    """问候用户，并指出其名字"""
    username = get_stored_username()
    if username:
        answer = input("If the name {} is right?(yes(default)/no)".format(username))
        if answer.lower() == ('yes' or 'y'):
            print("Welcome back {}.".format(username))
        elif answer.lower() == ('no' or 'n'):
            username = get_new_username()
            print("We'l remember you when you come back {}".format(username))
        else:
            print("Welcome back {}.".format(username))
    else:
        username = get_new_username()
        print("We'l remember you when you come back {}".format(username))

greet_user()
